import axios from 'axios'
import { ElMessage } from 'element-plus'
import {HttpStatus} from '@/utils/enum/HttpStatus'
import { useUserStore } from '@/stores/user'
import router from '@/router/index'

// 创建 axios 实例
const service = axios.create({
  baseURL: '/api', // 基础URL
  timeout: 15000 // 请求超时时间
})

// request 拦截器
service.interceptors.request.use(
  config => {
    // 设置除了/public接口，其他接口都需要添加token请求头
    if (config.url &&!config.url.includes('/public')) {
      const userStore = useUserStore()
      if (userStore.getToken) {
        config.headers['Authorization'] = `Bearer ${userStore.getToken}`
      }
    }
    // 添加时间戳防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.parse(new Date()) / 1000
      }
    }
    return config
  },
  error => {
    console.log('request error:', error)
    ElMessage.error('请求异常')
    return Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code && res.code !== 200) { 
      if(res.code === HttpStatus.WARN){
        ElMessage.warning(res.message)
      }
    }else{
      if (res.isShowMsg) {
        ElMessage.success(res.msg || '操作成功')
      }
    }
    return res
  },
  error => {
    console.log(error);
    
    if(error.status===401){
      const userStore = useUserStore()
      userStore.clearUserData()
      router.push('/login')
    }
    ElMessage.error(error.response.data || "服务异常" )
    return Promise.reject(error)
  }
)

export default service